<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="css/index.css">
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <title>Go Playground</title>
</head>
<body>

<div style="background-color: beige" class="main">
    <label for="code" id="codeLabel">Go Playground</label>
    <textarea name="code" id="code">
package main

import (
	"fmt"
)

func main() {
	fmt.Println("Hello, World !")
}
    </textarea>
    <div class="result">

    </div>
    <button class="btnRun" onclick="app.run()">Run</button>
    <button class="btnFormat" onclick="app.format()">Format</button>
    <span class="statusBar" id="status"></span>
</div>

<script>

    function Index() {

        // 运行代码
        this.run = function () {
            let code = document.getElementById('code').value;
            document.getElementById('status').innerHTML = 'Waiting Remote Server Response ...';
            $.ajax('/action.php', {
                type: 'POST',
                data: {
                    action: 'run',
                    code: code
                },
                success: function (data, status, code) {
                    document.getElementsByClassName('result')[0].innerHTML = data.res.join("<br>");
                    document.getElementById('status').innerHTML = 'Program Run Finished.';
                },
                fail: function (data, status, code) {
                    document.getElementById('status').innerHTML = "Request Failed...";
                }
            });
        };

        // 格式化代码
        this.format = function () {
            let code = document.getElementById('code').value;
            document.getElementById('status').innerHTML = 'Waiting Remote Server Response ...';
            $.ajax('/action.php', {
                type: 'POST',
                data: {
                    action: 'format',
                    code: code
                },
                success: function (data, status, code) {
                    document.getElementsByClassName('result')[0].innerHTML = data.err.join("<br>");
                    document.getElementById('code').value = data.res;
                    document.getElementById('status').innerHTML = 'Code Format Successfully !';
                },
                fail: function (data, status, code) {
                    document.getElementById('status').innerHTML = "Request Failed...";
                }
            });
        };

    }

    let app = new Index();

</script>

</body>
</html>